<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <title>二维码扫描演示</title>
</head>

<body>
    <style>
        canvas {
            display: none;
        }

        hr {
            margin-top: 32px;
        }

        input[type="file"] {
            display: block;
            margin-bottom: 16px;
        }

        div {
            margin-bottom: 16px;
        }
    </style>
    <h1>使用摄像头扫描:</h1>
    <div>
        <b>是否有摄像头: </b>
        <span id="cam-has-camera"></span>
        <br>
        <video muted playsinline id="qr-video"></video>
    </div>
    <div>
        <select id="inversion-mode-select">
            <option value="original">扫描原稿（明亮背景上的深色QR码）</option>
            <option value="invert">使用反色扫描（深色背景上的明亮QR码）</option>
            <option value="both">自适应</option>
        </select>
        <br>
    </div>
    <b>扫描内容: </b>
    <span id="cam-qr-result">暂无</span>
    <br>
    <b>最后扫描时间: </b>
    <span id="cam-qr-result-timestamp"></span>
    <hr>

    <h1>使用文件扫描:</h1>
    <input type="file" id="file-selector">
    <b>扫描内容: </b>
    <span id="file-qr-result">暂无</span>

    <script type="module">
        import QrScanner from "../js/qr-scanner.min.js";
        QrScanner.WORKER_PATH = '../js/qr-scanner-worker.min.js';

        const video = document.getElementById('qr-video');
        const camHasCamera = document.getElementById('cam-has-camera');
        const camQrResult = document.getElementById('cam-qr-result');
        const camQrResultTimestamp = document.getElementById('cam-qr-result-timestamp');
        const fileSelector = document.getElementById('file-selector');
        const fileQrResult = document.getElementById('file-qr-result');

        function setResult(label, result) {
            label.textContent = result;
            camQrResultTimestamp.textContent = new Date().toLocaleString();
            label.style.color = 'blue';
            clearTimeout(label.highlightTimeout);
            label.highlightTimeout = setTimeout(() => label.style.color = 'inherit', 100);
        }

        // ####### Web 摄像头扫描 #######

        QrScanner.hasCamera().then(hasCamera => camHasCamera.textContent = hasCamera);

        const scanner = new QrScanner(video, result => setResult(camQrResult, result));
        scanner.start();

        document.getElementById('inversion-mode-select').addEventListener('change', event => {
            scanner.setInversionMode(event.target.value);
        });

        // ####### 文件扫描 #######

        fileSelector.addEventListener('change', event => {
            const file = fileSelector.files[0];
            if (!file) {
                return;
            }
            QrScanner.scanImage(file)
                .then(result => setResult(fileQrResult, result))
                .catch(e => setResult(fileQrResult, e || '未找到二维码'));
        });

    </script>
</body>

</html>